import Vue from 'vue'
import router from './../router/index';
import CryptoJS from 'crypto-js'
import environment from './environment'
import { ToastPlugin } from 'vux'

Vue.use(ToastPlugin,{position: 'top'});
var tools = {
    baseUrl(){
        return 'http://117.78.38.213:7001'
    },

    //跳转页面,不带查询参数
    goPage(name) {
        router.push({
            name: name
        })
    },

    //跳转页面,带查询参数,query为对象， {id:1}
    goPage_query(name, query) {
        router.push({
            name: name,
            query: query,
        })
    },

    // 将数据存入localStorage
    setMessage(paramName,paramValue){
        window.localStorage.setItem(paramName,paramValue)
    },

    // 将数据从localStorage取出来
    getMessage(paramName){
      return  window.localStorage.getItem(paramName)
    },

    // 对密码进行加密
    saltpwd(pwd) {
        return CryptoJS.SHA256(environment['salt'] + pwd).toString(CryptoJS.enc.Hex);
    },

    invokeUAF(method, params) {
        return tools.invoke(method, params, 'uaf');
    },

    invoke(method, params) {
        if (localStorage.getItem('uat') != null) {
            params.uat = localStorage.getItem('uat');
        }
        if (localStorage.getItem('regioncode') != null) {
            params.webRegioncode = localStorage.getItem('regioncode');
        }
        // params.appcode = "h5";
        params.appcode = "appcode_test0000";
        params.rnd = Math.random() * 99999998 + 1;
        params.ts = new Date().getTime();
        let str = tools.objKeySortexclude(params, "sig");
        let sig1 = "/" + method + "?" + str;
        console.log(sig1, 'sig1')
        let sig = CryptoJS.HmacSHA1(sig1, "MjGr2[214fTec.mGq.appkey");
        let ss = sig.toString(CryptoJS.enc.Hex);
        params.sig = ss;
        console.log(ss, 'ss')
        let finalparams = tools.objKeySort(params);
        return finalparams;
    },


    /**
     * 参数排序,拼接
     * @param arys
     */
    objKeySort(arys) {
        let newkey = Object.keys(arys).sort();
        let parStr = "";
        for (var i = 0; i < newkey.length; i++) {
            parStr += newkey[i] + "=" + arys[newkey[i]] + "&";
        }
        return parStr == "" ? "" : parStr = parStr.substr(0, parStr.length - 1); //返回排好序的新参数
    },

    objKeySortexclude(arys, exclude) {
        let newkey = Object.keys(arys).sort();
        let parStr = "";
        for (var i = 0; i < newkey.length; i++) {
            if (newkey[i] == exclude) {
                continue;
            }
            parStr += newkey[i] + "=" + arys[newkey[i]] + "&";
        }
        return parStr == "" ? "" : parStr = parStr.substr(0, parStr.length - 1); //返回排好序的新参数
    },

    // 上传文件
    uploadFiles(url, form) {
        alert(form)
        $.ajax({
            url: tools.baseUrl() + url,
            type: "post",
            data: form,
            processData: false,
            contentType: false,
            success: function (data) {
                return data
            },
            error: function (e) {
                Vue.$vux.toast.show({type: 'text', text: '上传图片失败,请稍再试', position: 'middle',})
                return ''
            }
        });
    },

    // 上传图片
    previewImg(e, showId, inputId, imgWidth) {
        let _showId = '#' + showId;
        let files = e.target.files;
        let tempWidth;
        let tempHeight;
        let type = "";
        if (files[0].type) {
            let _index = files[0].type.indexOf('/');
            type = files[0].type.slice(_index + 1, files[0].type.length)
        }
        let img = new Image;
        if (window.URL) {
            img.src = window.URL.createObjectURL(files[0]);
            let size = files[0].size;
            img.onload = function (e) {
                window.URL.revokeObjectURL(img.src);
                tempWidth = imgWidth;
                tempHeight = img.height * tempWidth / img.width;
                img.style.width ='100%';
                img.style.height = tempHeight + 'px';
                img.style.maxHeight = '240px';
                img.alt = img.width + 'x' + img.height
                $(_showId).append(img);
            }
        } else {
            e.target.select();
            e.target.blur();
            let nfile = document.selection.createRange().text;
            document.selection.empty();
            img.src = nfile;
            img.onload = function () {
            }
            $(_showId).append(img);
        }
    },

    // 删除上传的图片
    deleteImg(clear_file, remove_img) {
        $(clear_file).val('')
        $(remove_img).children('img').remove();
    },

    //将时间戳转化成年月日，时分秒，毫秒（保留三位小数（微妙））级 eg 2017-05-21 02:03:49
    formateChooseTime(time) {
        let newDate = new Date(time);
        let y = newDate.getFullYear();
        let m = newDate.getMonth() + 1;
        let d = newDate.getDate();
        // let h = newDate.getHours();
        // let min = newDate.getMinutes();
        // let s = newDate.getSeconds();
        m = m < 10 ? ("0" + m) : m;
        d = d < 10 ? ("0" + d) : d;
        // h = h < 10 ? ("0" + h) : h;
        // min = min < 10 ? ("0" + min) : min;
        // s = s < 10 ? ("0" + s) : s;
        // return new Date(y, m, d, h, min)
        // return  [y + "-" + m + "-" + d , h + ':' + min + ':' + s]
      return  y + "-" + m + "-" + d;
    },

}

export default tools
